<template>
  <div class="container">
    <!--  天气粒子  -->
    <WeatherParticles
        v-if="weatherData.loaded && isRainOrSnow"
        :type="particleType"
    />
    <!-- 天气卡片 -->
    <div class="weather-card" v-if="weatherData.loaded">
      <!-- 城市栏 -->
      <div class="city-bar">
        <i class="fa-solid fa-location-dot"></i>
        <span>{{ cityName }}</span>
      </div>
      <!-- ① 主天气 -->
      <section class="weather-main">
        <i :class="weatherIcon"></i>
        <div class="temp">{{ temp }}°C</div>
        <div class="desc">{{ weatherData.data.weather[0]?.description || '--' }}</div>
      </section>

      <!-- ② 体感/湿度/气压 -->
      <section class="weather-sub">
        <div class="sub-item">
          <i class="fa-solid fa-temperature-half"></i>
          <span>体感</span>
          <strong>{{ feelsLike }}°C</strong>
        </div>
        <div class="sub-item">
          <i class="fa-solid fa-droplet"></i>
          <span>湿度</span>
          <strong>{{ weatherData.data.main?.humidity || '--' }}%</strong>
        </div>
        <div class="sub-item">
          <i class="fa-solid fa-gauge"></i>
          <span>气压</span>
          <strong>{{ weatherData.data.main?.pressure || '--' }} hPa</strong>
        </div>
      </section>

      <!-- ③ 风速/风向/能见度/云量 -->
      <section class="weather-detail">
        <div class="detail-item">
          <i class="fa-solid fa-wind"></i>
          <span>风速</span>
          <strong>{{ weatherData.data.wind?.speed || '0' }} m/s</strong>
        </div>
        <div class="detail-item">
          <i class="fa-solid fa-location-arrow"></i>
          <span>风向</span>
          <strong>{{ weatherData.data.wind?.deg ?? '--' }}°</strong>
        </div>
        <div class="detail-item">
          <i class="fa-solid fa-eye"></i>
          <span>能见度</span>
          <strong>{{ vis }} km</strong>
        </div>
        <div class="detail-item">
          <i class="fa-solid fa-cloud"></i>
          <span>云量</span>
          <strong>{{ weatherData.data.clouds?.all || '0' }}%</strong>
        </div>
      </section>

      <div class="travel-tip" v-if="travelTip">
        <i class="fa-solid fa-lightbulb"></i>
        <span>{{ travelTip }}</span>
      </div>

      <div class="cloud-float">
        <i class="fa-solid fa-cloud"></i>
        <i class="fa-solid fa-cloud"></i>
      </div>
    </div>
    <div class="weather-card" v-if="!weatherData.loaded" >
      <i class="el-icon-loading" style="font-size:20px"></i>
      <span style="margin-left:8px;">天气加载中…</span>
    </div>
    <div style="width: 100%; padding: 10px 20px; font-size: 24px; background-color: rgba(0,0,0,.3); color: white; position: absolute; top: 0">企业固定资产管理系统</div>
    <div style="width: 350px; padding: 30px; background-color: rgba(255, 255, 255, .8); border-radius: 5px;">
      <div class="login-title">
        <img src="@/assets/imgs/EFAM.png" alt="logo"/>
        <span style="font-family: 微软雅黑">固定资产管理系统</span>
      </div>
<!--      <div style="text-align: center; font-size: 24px; margin-bottom: 30px; color: #333">欢迎使用</div>-->
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item prop="username">
          <el-input size="medium" prefix-icon="el-icon-user" clearable placeholder="请输入账号" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="medium" prefix-icon="el-icon-lock" clearable placeholder="请输入密码" show-password v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item prop="role">
          <el-select v-model="form.role">
            <el-option value="ADMIN" label="管理员"></el-option>
            <el-option value="STAFF" label="员工"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>

          <div style="display: flex; justify-content: center; gap: 20px;">
<!--            <el-button type="success" size="small" @click="wechatLogin" icon="el-icon-chat-dot-round">-->
<!--              企业微信登录-->
<!--            </el-button>-->
<!--            <el-button type="primary" size="small" @click="dingTalkLogin" icon="el-icon-message">-->
<!--              钉钉登录-->
<!--            </el-button>-->
            <el-button type="success" size="medium" @click="wechatLogin" icon="el-icon-chat-dot-round">
              微信登录
            </el-button>
            <el-button type="warning" size="medium" icon="el-icon-message" @click="$router.push('/emailLogin')">邮箱登录</el-button>
          </div>

          <!-- 二维码弹窗 -->
          <el-dialog title="请使用微信扫码" :visible.sync="showQR" width="300px" @close="clean">
            <div id="qrcode" style="margin:0 auto;width:200px;height:200px;"></div>
          </el-dialog>

        </el-form-item>
        <el-form-item>
          <div style="display: flex; align-items: center">
            <div style="flex: 1">
              <el-input size="medium" v-model="code" clearable placeholder="请输入验证码"></el-input>
            </div>
            <Identify @click.native="refreshCode" :identify-code="identifyCode"/>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" style="width: 100%; background-color: #313131; border-color: #313131; color: white" @click="login">登 录</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" @click="$router.push('/register')">注 册</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import Identify from "@/components/Identify";
import { pinyin } from 'pinyin-pro';
import QRCode from 'qrcodejs2'
import axios from "axios";

import WeatherParticles from '@/components/WeatherParticles.vue'

export default {
  name: "Login",
  components: {
    Identify,
    WeatherParticles,
  },
  data() {
    return {
      form: { role: 'STAFF' },
      code: '',
      identifyCode: '',
      identifyCodes: '3456789ABCDEFGHGKMNPQRSTUVWXY',
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ]
      },
      // 重构 weatherData
      weatherData: {
        loaded: false,
        data: {
          weather: [{ description: '' }],
          main: { temp: '', feels_like: '', humidity: '', pressure: '' },
          wind: { speed: 0, deg: 0, gust: 0 },
          clouds: { all: 0 },
          visibility: 0
        }
      },
      locationCity: '',
      showQR: false,
      scene: '',
      timer: null,
    };
  },
  computed: {
    // 是否下雨或下雪
    isRainOrSnow() {
      const id = this.weatherData.data.weather?.[0]?.id || 800
      return true
    },
    // 粒子类型
    particleType() {
      const id = this.weatherData.data.weather?.[0]?.id || 800
      return id >= 600 && id < 700 ? 'snow' : 'snow'
    },
    travelTip() {
      // 写死建议表：温度区间 + 关键词 → 一句话
      const TIP_MAP = [
        // 0℃ 以下
        { min: -99, max: -1, tip: '路面可能结冰，出行请穿防滑靴子，小步慢走；穿衣建议羽绒服加羊毛衫，戴围巾手套，注意耳朵防冻。' },
        // 0-5℃ 雨雪
        { min: 0, max: 5, key: /雪|雨/, tip: '道路湿滑，请备折叠伞，穿防滑鞋，减速慢行；穿衣选羽绒服内搭抓绒，下装加绒裤，戴帽子防风。' },
        // 0-5℃ 无雨雪
        { min: 0, max: 5, tip: '清晨傍晚寒冷，建议公交或地铁出行；穿衣选长款羽绒服加毛衣，围巾护颈，手套不可少。' },
        // 6-14℃ 大风
        { min: 6, max: 14, wind: 8, tip: '北风较大，避免骑行，可选公交地铁；穿衣选防风衣加毛衣，戴墨镜口罩防风沙，围巾固定。' },
        // 6-14℃ 普通
        { min: 6, max: 14, tip: '天气凉爽，适合步行或共享单车；穿衣选薄羽绒服或呢大衣，内搭长袖衬衫，早晚可加围巾。' },
        // 15-20℃ 小雨
        { min: 15, max: 20, key: /雨/, tip: '小雨淅沥，出门带伞，穿防滑鞋，慢步行车；穿衣选风衣加薄针织衫，下装休闲裤，备薄外套。' },
        // 15-20℃ 晴或多云
        { min: 15, max: 20, key: /云|晴/, tip: '温度舒适，适合骑行或漫步；穿衣选长袖衬衫加薄风衣，下装单裤，可备马甲随时增减。' },
        // 21-26℃ 晴
        { min: 21, max: 26, key: /晴/, tip: '阳光温和，适合户外步行或骑行；穿衣选短袖加薄外套，下装休闲裤，戴遮阳帽防晒。' },
        // 21-26℃ 阴
        { min: 21, max: 26, tip: '体感凉爽，适合慢跑或公交出行；穿衣选长袖衬衫单穿，下装薄长裤，带薄外套备用。' },
        // 27-32℃ 晴
        { min: 27, max: 32, key: /晴/, tip: '紫外线强，建议上午十点前或下午四点后出行，戴遮阳帽；穿衣选透气短袖加防晒服，下装轻薄短裤。' },
        // 27-32℃ 多云
        { min: 27, max: 32, tip: '午后闷热，尽量地铁公交，减少步行；穿衣选速干短袖加薄防晒衣，下装宽松短裤，勤补水。' },
        // 33℃ 以上
        { min: 33, max: 99, tip: '高温酷暑，避免长时间户外，优先地铁打车；穿衣选透气速干短袖加防晒袖套，戴遮阳帽墨镜，多饮水防中暑。' },
        // 大风兜底
        { wind: 8, tip: '风力较大，避免骑行，选择公交地铁；穿衣选防风衣或厚实外套，戴墨镜口罩防风沙，固定好帽子。' },
        // 普通雨天
        { key: /雨/, tip: '记得随身携带折叠伞，穿防滑鞋，慢步通过积水；穿衣选防风外套加长袖，下装速干长裤，备干毛巾。' },
        // 终极兜底
        { tip: '天气适宜，出行请注意安全，合理规划路线；穿衣选当季长袖加薄外套，下装舒适长裤，随时增减衣物。' }
      ];
      function getTip(temp, desc, wind) {
        const t = Number(temp), w = Number(wind), d = desc || '';
        for (const rule of TIP_MAP) {
          if ((rule.min === undefined || t >= rule.min) &&
              (rule.max === undefined || t <= rule.max) &&
              (rule.wind === undefined || w >= rule.wind) &&
              (rule.key === undefined || rule.key.test(d)))
            return rule.tip;
        }
        return '注意天气变化，平安出行';
      }
      if (!this.weatherData.loaded) return '';
      return getTip(
          this.temp,
          this.weatherData.data.weather?.[0]?.description || '',
          this.weatherData.data.wind?.speed || 0
      );
    },
    cityName() {
      // 你早已拿到的 locationData.city
      // 如果接口没返回就兜底
      return this.locationCity || '未知';
    },
    // 温度转成摄氏度并保留 1 位
    temp() {
      const k = this.weatherData.data.main?.temp;
      return k ? (k - 273.15).toFixed(1) : '--';
    },
    feelsLike() {
      const k = this.weatherData.data.main?.feels_like;
      return k ? (k - 273.15).toFixed(1) : '--';
    },
    // 能见度 m -> km
    vis() {
      const v = this.weatherData.data.visibility;
      return v ? (v / 1000).toFixed(1) : '--';
    },
    // 根据天气 id 选图标
    weatherIcon() {
      const id = this.weatherData.data.weather?.[0]?.id;
      if (!id) return 'fa-solid fa-question';
      if (id >= 200 && id < 300) return 'fa-solid fa-bolt';      // 雷暴
      if (id >= 300 && id < 600) return 'fa-solid fa-cloud-rain';// 雨
      if (id >= 600 && id < 700) return 'fa-solid fa-snowflake'; // 雪
      if (id >= 700 && id < 800) return 'fa-solid fa-smog';      // 霾
      if (id === 800) return 'fa-solid fa-sun';                  // 晴
      if (id > 800) return 'fa-solid fa-cloud';                  // 云
      return 'fa-solid fa-question';
    }
  },
  created() {
    this.refreshCode();
    this.fetchWeather();
  },
  methods: {
    refreshCode() {
      this.identifyCode = '';
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[Math.floor(Math.random() * (this.identifyCodes.length))];
      }
    },
    async fetchWeather() {
      try {
        // 获取天气接口配置
        const response = await this.$request.get('/apiConfig/selectByType/外部接口');
        const weatherApiConfig = response.data.find(api => api.name === 'OpenWeather-实时天气');
        // const locationApiConfig = response.data.find(api => api.name === '获取位置');
        const locationApiConfig = response.data.find(api => api.name === '获取用户位置');

        if (!weatherApiConfig || !locationApiConfig) {
          console.error('未找到天气接口配置');
        }

        // 获取用户位置
        const locationResponse = await this.$request.post('/apiConfig/test/' + locationApiConfig.id);
        const locationData = JSON.parse(locationResponse.data);
        this.locationCity = locationData.city + ',' + locationData.region + ',' + locationData.country;
        // this.locationCity = locationData.regionName + locationData.city;
        console.log(locationData.city)

        // ✅ 把中文城市名转为拼音（无音调、无空格）
        const cityPinyin = pinyin(locationData.city, {
          toneType: 'none',
          type: 'array'
        }).join('');

        console.log('原始城市:', locationData.city);     // 清泉
        console.log('拼音城市:', cityPinyin);           // qingquan

        // 设置天气查询参数
        const weatherParams = {
          q: cityPinyin,
          appid: JSON.parse(weatherApiConfig.auth_info).api_key,
        };
        const qs = new URLSearchParams(weatherParams).toString();

        // 调用天气API
        // const weatherResponse = await this.$request.post('/apiConfig/test/' + weatherApiConfig.id, { params: weatherParams });
        const weatherResponse = await this.$request.post(`/apiConfig/test/${weatherApiConfig.id}?${qs}`);
        console.log(JSON.parse(weatherResponse.data));
        const d = JSON.parse(weatherResponse.data);
        this.weatherData.data = {
          weather: d.weather || [{ description: '无数据' }],
          main: d.main || {},
          wind: d.wind || {},
          clouds: d.clouds || {},
          visibility: d.visibility || 0
        };

        // 确保数据加载完成后再设置loaded为true
        this.weatherData.loaded = true;
      } catch (error) {
        console.error('Error fetching weather data:', error);
        // 如果发生错误，也确保loaded为true，避免界面卡住
        this.weatherData.loaded = true;
      }
    },
    login() {
      if (this.code.toLowerCase() !== this.identifyCode.toLowerCase()) {
        this.$message.warning("验证码错误");
        this.refreshCode();
        this.code = '';
        return;
      }
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.form.role = 'STAFF';
          this.$request.post('/login', this.form).then(res => {
            if (res.code === '200') {
              localStorage.setItem("xm-user", JSON.stringify(res.data));
              this.$router.push('/');
              this.$message.success('登录成功');
            } else {
              this.refreshCode();
              this.code = '';
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    wechatLogin() {
      this.scene = Math.random().toString(36).slice(2)        // 随机串
      this.showQR = true
      this.$nextTick(() => {
        document.getElementById('qrcode').innerHTML = ''      // 清空旧码
        new QRCode(document.getElementById('qrcode'), {
          text: `https://dated-nonparabolically-zackary.ngrok-free.dev/getInfoRegister?scene=${this.scene}`,
          width: 200,
          height: 200
        })
        this.timer = setInterval(() => {
          this.$request.get(`/scanResult?scene=${this.scene}`).then(res => {
            if (res.code === '200') {
              console.log('拿到token', res.data.token)
              localStorage.setItem('xm-user', JSON.stringify(res.data))
              this.$message.success('登录成功')
              this.clean()
              console.log('准备跳转')
              this.$router.push('/')
            }
          })
        }, 1000)
      })
    },
    clean() {
      this.showQR = false
      clearInterval(this.timer)
      this.timer = null
    }
  },
  beforeDestroy() {
    this.clean()
  },
    // wechatLogin() {
    //   this.$request.get('/integration/wechat/authUrl', {
    //     params: {
    //       redirectUri: encodeURIComponent(window.location.origin + '/wechat-callback')
    //     }
    //   }).then(res => {
    //     if (res.code === '200') {
    //       window.location.href = res.data;
    //     } else {
    //       this.$message.error('获取企业微信授权URL失败');
    //     }
    //   });
    // },
    // dingTalkLogin() {
    //   this.$message.info('钉钉登录功能待实现');
    // },
}
</script>

<style scoped>
.container {
  height: 100vh;
  overflow: hidden;
  background-image: url("../assets/imgs/loginBack.png");
  background-size: 95%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}
.login-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 30px;
}
.login-title img {
  height: 42px;
  width: auto;
}
.login-title span {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  letter-spacing: 1px;
}
a {
  color: #2a60c9;
}
.weather-card {
  font-family: 微软雅黑;
  margin-top: 50px;
  position: absolute;
  top: 20px;
  left: 50px;
  width: 300px;                 /* 原来 300 → 360 */
  background: rgba(0, 0, 0, 0.65);
  color: #fff;
  backdrop-filter: blur(6px);
  border-radius: 16px;          /* 更大圆角 */
  padding: 24px;                /* 内边距 16 → 24 */
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
  font-size: 15px;              /* 字号 14 → 15 */
  display: flex;                /* 改用列布局 */
  flex-direction: column;
  gap: 18px;                    /* 每大区之间空 18px */
}
/* 三朵云横向均匀排布 */
.cloud-float{
  margin-top: 12px;
  display: flex;                 /* 横向排列 */
  justify-content: space-between;/* 均匀间距，也可改成 center / gap */
  align-items: center;
  font-size: 32px;
  color: rgba(255,255,255,.6);
  animation: float 3s ease-in-out infinite;
}
/* 每朵云单独给点延迟，看起来更自然 */
.cloud-float i:nth-child(2){ animation-delay: .2s; }
.cloud-float i:nth-child(3){ animation-delay: .4s; }

@keyframes float{
  0%,100%{ transform: translateY(0); }
  50%{ transform: translateY(-8px); }
}
/* 城市栏 */
.city-bar{
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 10px;
  font-size: 15px;
  opacity: .9;
}
.city-bar i{
  color: #ffd54f;          /* 小图标暖黄色 */
  font-size: 16px;
}
</style>